package com.luojialong.onlineJudge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luojialong.onlineJudge.common.ErrorCode;
import com.luojialong.onlineJudge.constant.CommonConstant;
import com.luojialong.onlineJudge.exception.BusinessException;
import com.luojialong.onlineJudge.judge.JudgeService;
import com.luojialong.onlineJudge.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.luojialong.onlineJudge.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.luojialong.onlineJudge.model.entity.Question;
import com.luojialong.onlineJudge.model.entity.QuestionSubmit;

import com.luojialong.onlineJudge.model.entity.User;
import com.luojialong.onlineJudge.model.enums.QuestionSubmitLanguageEnum;
import com.luojialong.onlineJudge.model.enums.QuestionSubmitStatusEnum;
import com.luojialong.onlineJudge.model.vo.QuestionSubmitVO;

import com.luojialong.onlineJudge.queue.OjMessageProducer;
import com.luojialong.onlineJudge.service.QuestionService;
import com.luojialong.onlineJudge.service.QuestionSubmitService;

import com.luojialong.onlineJudge.mapper.QuestionSubmitMapper;
import com.luojialong.onlineJudge.service.UserService;
import com.luojialong.onlineJudge.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;

import java.util.List;

import java.util.stream.Collectors;


@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;


    @Autowired
    private UserService userService;


    @Autowired
    @Lazy
    private JudgeService judgeService;

    @Resource
    private OjMessageProducer ojMessageProducer;


    @Autowired
    private QuestionSubmitMapper questionSubmitMapper;
    /**
     * 题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmit doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编译语言错误");
        }
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //把名字为rhb的用户年龄更新为18，其他属性不变
        UpdateWrapper<Question> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",question.getId());
        Question updateQuestion = new Question();
        if (question.getSubmitNum() == null) {
            updateQuestion.setSubmitNum(1);
        }else {
            updateQuestion.setSubmitNum(question.getSubmitNum() + 1);
        }
        boolean update = questionService.update(updateQuestion, updateWrapper);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目提交失败");
        }
        // 是否已题目
        long userId = loginUser.getId();

        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WARNING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean result = this.save(questionSubmit);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();
//        CompletableFuture.runAsync(()-> {
//            judgeService.doJudge(questionSubmitId);
//        });
//        ojMessageProducer.sendMessage("luojialong","shenming",String.valueOf(questionSubmitId));
        return judgeService.doJudge(questionSubmitId);
    }


    /**
     * 获取查询包装类
     * 获取查询包装类(用户根据那些字段查询,根据前端传来的请求对象,得到mybatis 框架支持的查询QueryWrapper类)
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.like(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.like(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        long userId = loginUser.getId();
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser)).collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    @Override
    public void updateIntegral(Long userId, Question question) {
        QueryWrapper<QuestionSubmit> wrapper = new QueryWrapper<>();
        wrapper.eq("status",2);
        wrapper.eq("userId",userId);
        wrapper.eq("questionId",question.getId());
        List<QuestionSubmit> questionSubmitList = questionSubmitMapper.selectList(wrapper);
        User user = userService.getById(userId);
        if (questionSubmitList == null || questionSubmitList.isEmpty()) {
            User updateUser = new User();
            updateUser.setId(userId);
            updateUser.setIntegral(user.getIntegral() + question.getIntegral());
            userService.updateById(updateUser);
            userService.update();
        }
    }
}










